package com.xchb.im.conne.utils;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author XDD
 * @project muchat
 * @date 2021/7/24
 * @description Good Good Study,Day Day Up.
 */
@Component
@Slf4j
public class UserConnectionHolder {

    //存储通道消息：通道id：Channel
    private static final Map<String, Channel> CONNECTION_CONTAIL = new ConcurrentHashMap<>();

    //存储用户与通道的对应关系: 用户id：通道id
    private static final Map<String, String> tmp = new ConcurrentHashMap<>();


    public void loginout(String channelId) {
        CONNECTION_CONTAIL.remove(channelId);
    }

    public void login(String userId, Channel channel) {
        String channelId = channel.id().asLongText();
        tmp.put(userId,channelId);
        CONNECTION_CONTAIL.put(channelId,channel );
    }


    public void send(String userId, String msg) {
        String chanelId = tmp.get(userId);
        if(chanelId==null){
            return;
        }
        Channel channel = CONNECTION_CONTAIL.get(chanelId);
        if(channel!=null && channel.isOpen()){
            channel.writeAndFlush(new TextWebSocketFrame(msg));
            log.info("推送成功：{}",msg);
        }

    }
}
